import datashader as ds
import datashader.transfer_functions as tf
import datashader.glyphs
from datashader import reductions
from datashader.core import bypixel
from datashader.utils import lnglat_to_meters as webm, export_image
from datashader.colors import colormap_select, Greys9, viridis, inferno
import copy
from pyproj import Proj, transform
import numpy as np
import pandas as pd
import urllib
import json
import datetime
import colorlover as cl
import plotly.offline as py
import plotly.graph_objs as go
from plotly import tools
from shapely.geometry import Point, Polygon, shape
# In order to get shapley, you'll need to run [pip install shapely.geometry] from your terminal
from functools import partial
py.init_notebook_mode()
For module 2 we'll be looking at techniques for dealing with big data. In particular binning strategies and the datashader library (which possibly proves we'll never need to bin large data for visualization ever again.)
To demonstrate these concepts we'll be looking at the PLUTO dataset put out by New York City's department of city planning. PLUTO contains data about every tax lot in New York City.
PLUTO data can be downloaded from here. Unzip them to the same directory as this notebook, and you should be able to read them in using this (or very similar) code. Also take note of the data dictionary, it'll come in handy for this assignment.
# Code to read in v17, column names have been updated (without upper case letters) for v18
# bk = pd.read_csv('PLUTO17v1.1/BK2017V11.csv')
# bx = pd.read_csv('PLUTO17v1.1/BX2017V11.csv')
# mn = pd.read_csv('PLUTO17v1.1/MN2017V11.csv')
# qn = pd.read_csv('PLUTO17v1.1/QN2017V11.csv')
# si = pd.read_csv('PLUTO17v1.1/SI2017V11.csv')
# ny = pd.concat([bk, bx, mn, qn, si], ignore_index=True)
ny = pd.read_csv('//Users//sudhanmaharjan//Desktop//MSDS_DATA608_FALL2019//Module2//nyc_pluto_18v2_1_csv//pluto_18v2_1.csv')
# Getting rid of some outliers
ny = ny[(ny['yearbuilt'] > 1850) & (ny['yearbuilt'] < 2020) & (ny['numfloors'] != 0)]
I'll also do some prep for the geographic component of this data, which we'll be relying on for datashader.
You're not required to know how I'm retrieving the lattitude and longitude here, but for those interested: this dataset uses a flat x-y projection (assuming for a small enough area that the world is flat for easier calculations), and this needs to be projected back to traditional lattitude and longitude.
Part 1: Binning and Aggregation Binning is a common strategy for visualizing large datasets. Binning is inherent to a few types of visualizations, such as histograms and 2D histograms (also check out their close relatives: 2D density plots and the more general form: heatmaps.
While these visualization types explicitly include binning, any type of visualization used with aggregated data can be looked at in the same way. For example, lets say we wanted to look at building construction over time. This would be best viewed as a line graph, but we can still think of our results as being binned by year:
trace = go.Scatter(
# I'm choosing BBL here because I know it's a unique key.
x = ny.groupby('yearbuilt').count()['bbl'].index,
y = ny.groupby('yearbuilt').count()['bbl']
)
layout = go.Layout(
xaxis = dict(title = 'Year Built'),
yaxis = dict(title = 'Number of Lots Built')
)
fig = go.Figure(data = [trace], layout = layout)
py.iplot(fig)
Something looks off... You're going to have to deal with this imperfect data to answer this first question.
But first: some notes on pandas. Pandas dataframes are a different beast than R dataframes, here are some tips to help you get up to speed:
Hello all, here are some pandas tips to help you guys through this homework:
Indexing and Selecting: .loc and .iloc are the analogs for base R subsetting, or filter() in dplyr
Group By: This is the pandas analog to group_by() and the appended function the analog to summarize(). Try out a few examples of this, and display the results in Jupyter. Take note of what's happening to the indexes, you'll notice that they'll become hierarchical. I personally find this more of a burden than a help, and this sort of hierarchical indexing leads to a fundamentally different experience compared to R dataframes. Once you perform an aggregation, try running the resulting hierarchical datafrome through a reset_index().
Reset_index: I personally find the hierarchical indexes more of a burden than a help, and this sort of hierarchical indexing leads to a fundamentally different experience compared to R dataframes. reset_index() is a way of restoring a dataframe to a flatter index style. Grouping is where you'll notice it the most, but it's also useful when you filter data, and in a few other split-apply-combine workflows. With pandas indexes are more meaningful, so use this if you start getting unexpected results.
Indexes are more important in Pandas than in R. If you delve deeper into the using python for data science, you'll begin to see the benefits in many places (despite the personal gripes I highlighted above.) One place these indexes come in handy is with time series data. The pandas docs have a huge section on datetime indexing. In particular, check out resample, which provides time series specific aggregation.
Merging, joining, and concatenation: There's some overlap between these different types of merges, so use this as your guide. Concat is a single function that replaces cbind and rbind in R, and the results are driven by the indexes. Read through these examples to get a feel on how these are performed, but you will have to manage your indexes when you're using these functions. Merges are fairly similar to merges in R, similarly mapping to SQL joins.
Apply: This is explained in the "group by" section linked above. These are your analogs to the plyr library in R. Take note of the lambda syntax used here, these are anonymous functions in python. Rather than predefining a custom function, you can just define it inline using lambda.
Browse through the other sections for some other specifics, in particular reshaping and categorical data (pandas' answer to factors.) Pandas can take a while to get used to, but it is a pretty strong framework that makes more advanced functions easier once you get used to it. Rolling functions for example follow logically from the apply workflow (and led to the best google results ever when I first tried to find this out and googled "pandas rolling")
Google Wes Mckinney's book "Python for Data Analysis," which is a cookbook style intro to pandas. It's an O'Reilly book that should be pretty available out there.
Question
After a few building collapses, the City of New York is going to begin investigating older buildings for safety. The city is particularly worried about buildings that were unusually tall when they were built, since best-practices for safety hadn’t yet been determined. Create a graph that shows how many buildings of a certain number of floors were built in each year (note: you may want to use a log scale for the number of buildings). Find a strategy to bin buildings (It should be clear 20-29-story buildings, 30-39-story buildings, and 40-49-story buildings were first built in large numbers, but does it make sense to continue in this way as you get taller?)
#Import the required library
import matplotlib.pyplot as plt
import pandas as pd
# Brooklyn #
BK = pd.read_csv("/Users//sudhanmaharjan//Desktop//MSDS_DATA608_FALL2019//Module2//PLUTO17v1.1//BK2017V11.csv")
BK.head()
# Bronx #
BX = pd.read_csv("/Users//sudhanmaharjan//Desktop//MSDS_DATA608_FALL2019//Module2//PLUTO17v1.1//BX2017V11.csv")
BX.head()
# Manhattan #
MN = pd.read_csv("/Users//sudhanmaharjan//Desktop//MSDS_DATA608_FALL2019//Module2//PLUTO17v1.1//MN2017V11.csv")
MN.head()
# Queens #
QN = pd.read_csv("/Users//sudhanmaharjan//Desktop//MSDS_DATA608_FALL2019//Module2//PLUTO17v1.1//QN2017V11.csv")
QN.head()
# Staten Island
SI = pd.read_csv("/Users//sudhanmaharjan//Desktop//MSDS_DATA608_FALL2019//Module2//PLUTO17v1.1//SI2017V11.csv")
SI.head()
# create the combined dataframe of all boros
df_nyc_all_borough = pd.concat([BK,BX,MN,QN,SI],sort='False')
# Getting rid of some outliers
df_nyc_all_borough = df_nyc_all_borough[(df_nyc_all_borough['YearBuilt'] > 1850) & (df_nyc_all_borough['YearBuilt'] < 2020) & (df_nyc_all_borough['NumFloors'] != 0)]
df_nyc_all_borough.head()
df_yearBuilt = df_nyc_all_borough.loc[:, ['BBL','YearBuilt']]
df_yearBuilt.head()
df_yearBuilt_nonzeros = df_yearBuilt.replace(0, pd.np.nan).dropna(axis=0, how='any').fillna(0).astype(int)
df_yearBuilt_nonzeros.head()
import matplotlib.pyplot as plt
%matplotlib inline
df_yearBuilt_nonzeros.hist(column='YearBuilt', range=[1880,2020], bins =60,figsize=[10,8])
plt.grid(axis='y', alpha=1)
plt.xlabel("Year Built", labelpad=16)
plt.ylabel("Houses Built", labelpad=16)
plt.title("Houses built in different years", y=1.015, fontsize=18)
The hightest number of houses built were in the year 1920s to 1930s. Overall the peak time were from 1900s to 1960s.
df_yearBuilt_nonzeros.count()
# generate summary statistics of YearBuilt
print df_nyc_all_borough['YearBuilt'].describe()
In total 43699 records were of value 0 for YearBuilt that means the house built year was not known or there might have been error when data entry.
There is a record that YearBuilt is greater than 2025 which is not possible. We are in 2019 so there might have been error.
The houses built in different years seems little weird. There is no such thing that in certain years there was a boom in the housing and then later nothing happened. Housing business gradually grows and people start living on these. So let's figure out what can be done to make this dataset more meaningful.
#importing required libraries for the graph and later on
import copy
import urllib
import json
import plotly # offline plotly
import plotly.offline as py
import datetime
import numpy as np
import pandas as pd
import colorlover as cl
import chart_studio.plotly as py
import plotly.graph_objs as go
import datashader.transfer_functions as tf
from chart_studio.plotly import iplot
from plotly import tools
from functools import partial
from pyproj import Proj, transform
from bokeh.io import output_notebook, show # legend
from shapely.geometry import Point, Polygon, shape
from datashader.bokeh_ext import create_categorical_legend # legend
from datashader.utils import lnglat_to_meters as webm, export_image
from datashader.colors import colormap_select, Greys9, viridis, inferno
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot # offline plotly
df_nyc_all_borough = df_nyc_all_borough[(df_nyc_all_borough['YearBuilt'] > 1880) & (df_nyc_all_borough['YearBuilt'] < 2020) & (df_nyc_all_borough['NumFloors'] != 0)]
nyc_yearbuilt_decades = df_nyc_all_borough[['YearBuilt', 'NumFloors', 'BBL']].copy() # Avoid case where changing df1 also changes df
nyc_yearbuilt_decades['YearBuilt'] = (np.ceil(nyc_yearbuilt_decades['YearBuilt'] / 10.0).astype(int) * 10) # round up to next decade
#now creating the figures
trace = go.Bar(
x = nyc_yearbuilt_decades.groupby('YearBuilt').count()['BBL'].index,
y = nyc_yearbuilt_decades.groupby('YearBuilt').count()['BBL']
)
layout = go.Layout(
xaxis = dict(title = 'Built Decade'),
yaxis = dict(title = 'Number of Lots')
)
figure = go.Figure(data = [trace], layout = layout)
plotly.offline.plot(figure) # it creates a new temp-plot.html file for the graph
After represeting the data into graph for the above dataset it seems little off because it shows the builiding were built less after 1960 which is not possible. So,further we have make sure that the graph represents what exactly the data is.
We will be conducting the log on the dataset to see if it will make sense
height_distance = pd.DataFrame()
grouped = nyc_yearbuilt_decades.groupby(['YearBuilt', 'NumFloors'])
height_distance['Amount'] = grouped['NumFloors'].count()
subgrouped = height_distance.groupby(['YearBuilt'])['Amount']
height_distance['a'] = subgrouped.cumsum()/subgrouped.sum()
alpha = 0.02 # significance used to define unusual
height_distance['Unusual'] = height_distance['a'] > (1 - alpha)
height_distance.groupby(['YearBuilt','Unusual']).filter(lambda x:(x['Unusual']==True).all())
builtyear_unsual = height_distance.groupby(['YearBuilt','Unusual']).sum()['Amount']
#creating the graph
trace1 = go.Bar(
x = builtyear_unsual.unstack(level=-1)[False].index,
y = builtyear_unsual.unstack(level=-1)[False],
name='Bottom 99%'
)
trace2 = go.Bar(
x = builtyear_unsual.unstack(level=-1)[True].index,
y = builtyear_unsual.unstack(level=-1)[True],
name='Top 1%'
)
layout = go.Layout(
xaxis = dict(title = 'Built Decade'),
yaxis = dict(title = 'Height Distribution (Log)',
showticklabels=False,
type = "log",
hoverformat = '.0f'),
barmode = 'stack'
)
figure1 = go.Figure(data = [trace1, trace2], layout = layout)
plotly.offline.plot(figure1) # it creates a new temp-plot.html file for the graph
Now, let's group the floor of the buildings on the 10s value so that we can categorize it
nyc_binned_df = nyc_yearbuilt_decades.copy() # to avoid any changes on the previous df
building_floors = ((np.ceil(nyc_binned_df['NumFloors']) - 1) // 10 * 10 + 1).astype(int)
nyc_binned_df['Binned'] = ['{0:03d} to {1:03d} Floors'.format(x, x+9) for x in building_floors]
grouped = nyc_binned_df.groupby(['YearBuilt', 'Binned', 'NumFloors'])
nyc_building_floors = pd.DataFrame()
nyc_building_floors['Amount'] = grouped['NumFloors'].count()
floor_unstack = nyc_building_floors.groupby(['YearBuilt','Binned']).sum()['Amount'].unstack(level=-1, fill_value=0)
floor_unstack
Since we can see there are 0 values in different columns lets fix this and since thre is very less value from floor 61 to 120 we can combine all these columns and make it 61 and above to determine that these buildings are all tall and caterogized as one category
floor_unstack['061 to 120 Floors'] = floor_unstack[floor_unstack.columns[6:11]].sum(axis=1)
floor_unstack = floor_unstack.drop(columns=floor_unstack.columns[6:11]).replace(0, np.nan)
floor_unstack
Now lets graph the columns that we have just created
data = [] #dataframe info for traces
for i in range(0, len(floor_unstack.columns)):
trace = go.Bar(
x = floor_unstack[floor_unstack.columns[i]].index,
y = floor_unstack[floor_unstack.columns[i]],
name=floor_unstack.columns[i]
)
data.append(trace)
layout = go.Layout(
xaxis = dict(title = 'Built Decade'),
yaxis = dict(title = 'Number of Lots (Log)',
showticklabels=False,
type = "log",
hoverformat = '.0f'),
barmode = 'stack'
)
figure3 = go.Figure(data = data, layout = layout)
plotly.offline.plot(figure3) # it creates a new temp-plot.html file for the graph
Part 2: Datashader
Datashader is a library from Anaconda that does away with the need for binning data. It takes in all of your datapoints, and based on the canvas and range returns a pixel-by-pixel calculations to come up with the best representation of the data. In short, this completely eliminates the need for binning your data.
As an example, lets continue with our question above and look at a 2D histogram of YearBuilt vs NumFloors:
yearbins = 200
floorbins = 200
yearBuiltCut = pd.cut(df_nyc_all_borough['YearBuilt'], np.linspace(df_nyc_all_borough['YearBuilt'].min(), df_nyc_all_borough['YearBuilt'].max(), yearbins))
numFloorsCut = pd.cut(df_nyc_all_borough['NumFloors'], np.logspace(1, np.log(df_nyc_all_borough['NumFloors'].max()), floorbins))
xlabels = np.floor(np.linspace(df_nyc_all_borough['YearBuilt'].min(), df_nyc_all_borough['YearBuilt'].max(), yearbins))
ylabels = np.floor(np.logspace(1, np.log(df_nyc_all_borough['NumFloors'].max()), floorbins))
data = [
go.Heatmap(z = df_nyc_all_borough.groupby([numFloorsCut, yearBuiltCut])['BBL'].count().unstack().fillna(0).values,
colorscale = 'Viridis', x = xlabels, y = ylabels)
]
plotly.offline.plot(data) # it creates a new temp-plot.html file for the graph
Here is what the same plot would look like in datashader:
cvs = ds.Canvas(800, 500, x_range = (df_nyc_all_borough['YearBuilt'].min(), df_nyc_all_borough['YearBuilt'].max()),
y_range = (df_nyc_all_borough['NumFloors'].min(), df_nyc_all_borough['NumFloors'].max()))
agg = cvs.points(df_nyc_all_borough, 'YearBuilt', 'NumFloors')
view = tf.shade(agg, cmap = cm(Greys9), how='log')
export(tf.spread(view, px=3), 'yearvsnumfloors')
That's technically just a scatterplot, but the points are smartly placed and colored to mimic what one gets in a heatmap. Based on the pixel size, it will either display individual points, or will color the points of denser regions.
Datashader really shines when looking at geographic information. Here are the latitudes and longitudes of our dataset plotted out, giving us a map of the city colored by density of structures:
wgs84 = Proj("+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs")
nyli = Proj("+proj=lcc \
+lat_1=40.66666666666666 \
+lat_2=41.03333333333333 \
+lat_0=40.16666666666666 \
+lon_0=-74 \
+x_0=300000 \
+y_0=0 \
+ellps=GRS80 \
+datum=NAD83 \
+to_meter=0.3048006096012192 \
+no_defs")
df_nyc_all_borough['XCoord'] = 0.3048*df_nyc_all_borough['XCoord']
df_nyc_all_borough['YCoord'] = 0.3048*df_nyc_all_borough['YCoord']
df_nyc_all_borough['lon'], df_nyc_all_borough['lat'] = transform(nyli, wgs84, df_nyc_all_borough['XCoord'].values, df_nyc_all_borough['YCoord'].values)
df_nyc_all_borough = df_nyc_all_borough[(df_nyc_all_borough['lon'] < -60) & (df_nyc_all_borough['lon'] > -100) & (df_nyc_all_borough['lat'] < 60) & (df_nyc_all_borough['lat'] > 20)]
df_nyc_all_borough
#Defining some helper functions for DataShader
background = "black"
export = partial(export_image, background = background, export_path="export")
cm = partial(colormap_select, reverse=(background!="black"))
NewYorkCity = (( -74.29, -73.69), (40.49, 40.92))
cvs = ds.Canvas(700, 700, *NewYorkCity)
agg = cvs.points(df_nyc_all_borough, 'lon', 'lat')
view = tf.shade(agg, cmap = cm(inferno), how='log')
export(tf.spread(view, px=3), 'firery')
Interestingly, since we're looking at structures, the large buildings of Manhattan show up as less dense on the map. The densest areas measured by number of lots would be single or multi family townhomes.
Unfortunately, Datashader doesn't have the best documentation. Browse through the examples from their github repo. I would focus on the visualization pipeline and the US Census Example for the question below. Feel free to use my samples as templates as well when you work on this problem.
Question
You work for a real estate developer and are researching underbuilt areas of the city. After looking in the Pluto data dictionary, you've discovered that all tax assessments consist of two parts: The assessment of the land and assessment of the structure. You reason that there should be a correlation between these two values: more valuable land will have more valuable structures on them (more valuable in this case refers not just to a mansion vs a bungalow, but an apartment tower vs a single family home). Deviations from the norm could represent underbuilt or overbuilt areas of the city. You also recently read a really cool blog post about bivariate choropleth maps, and think the technique could be used for this problem.
Datashader is really cool, but it's not that great at labeling your visualization. Don't worry about providing a legend, but provide a quick explanation as to which areas of the city are overbuilt, which areas are underbuilt, and which areas are built in a way that's properly correlated with their land value.
#for the map of the NYC to display the density of buildings(tall buildings, private housese, town houses)
nyc_assessment = df_nyc_all_borough[['AssessTot', 'AssessLand','lon','lat']].copy() # to avoid any changes on previous df
nyc_assessment['AssessBldg'] = nyc_assessment['AssessTot'].sub(nyc_assessment['AssessLand'], axis=0)
labels = [['A', 'B', 'C'], ['1', '2', '3']] # three different classes in each variable
p = 100 / len(labels[0]) # percentile bins
q = np.percentile(nyc_assessment[['AssessLand', 'AssessBldg']], [p, 100 - p], axis=0) # breakpoints
nyc_assessment['Var1_Class'] = pd.cut(nyc_assessment['AssessLand'], [0, q[0][0], q[1][0], np.inf], right=False, labels=labels[0]) # bin
nyc_assessment['Var2_Class'] = pd.cut(nyc_assessment['AssessBldg'], [0, q[0][1], q[1][1], np.inf], right=False, labels=labels[1]) # bin
nyc_assessment['Bi_Class'] = nyc_assessment['Var1_Class'].astype(str) + nyc_assessment['Var2_Class'].astype(str)
nyc_assessment['Bi_Class'] = pd.Categorical(nyc_assessment['Bi_Class'])
nyc_assessment.head()
#sliced the data to our needed columns
nyc_assessment = nyc_assessment.loc[:, ['lon','lat','Bi_Class']]
nyc_assessment.head()
#lets bring the NYC into a map
NewYorkCity = (( -74.29, -73.69), (40.49, 40.92))
canvas = ds.Canvas(800, 800, * NewYorkCity)
agg = canvas.points(nyc_assessment, 'lon', 'lat', ds.count_cat('Bi_Class'))
agg
#to demonstrate different Bi_Class with different colors
cmap = {'A1': '#fcfbfd', 'A2': '#efedf5', 'A3': '#dadaeb',
'B1': '#bcbddc', 'B2': '#9e9ac8', 'B3': '#807dba',
'C1': '#6a51a3', 'C2': '#54278f', 'C3': '#3f007d'}
img = tf.shade(agg, color_key = cmap)
export(tf.spread(img, px=2),'Viridus')
Accoroding to the graph, it seems like Manhattan is highly crowed with tall buildings which makes sense. It is the city center of all the boroughs. Nearby part of Queens which is close to Manhattan has also tall buildings and Dumbo area in Brooklyn has all tall buildings according to the dense color in the map. As we can see some dense color in far Queens(Long Island border)area I am not sure about this because these are mostly residential area. There are lots of townhouses and private houses which are 2-3 storeys but in the map that area looks little dense.
References
https://plot.ly/python/offline/
https://plot.ly/ggplot2/geom_bar/
https://plot.ly/javascript/hover-events/
https://plot.ly/python/filled-area-plots/
https://pandas.pydata.org/pandas-docs/stable/categorical.html
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html